<template>
  <div class="workflows-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>流程列表</span>
          <div class="header-buttons">
            <el-upload
              class="upload-btn"
              :show-file-list="false"
              :before-upload="handleImport"
              accept=".xml"
            >
              <el-button type="primary">导入流程</el-button>
            </el-upload>
            <el-button type="primary" @click="handleAdd">新增流程</el-button>
          </div>
        </div>
      </template>

      <el-table :data="processList" v-loading="loading">
        <el-table-column prop="processName" label="流程名称" />
        <el-table-column prop="processKey" label="流程标识" />
        <el-table-column prop="version" label="版本号" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProcessList ,deleteProcess} from '../../../api/workflow'

const route = useRoute()
const router = useRouter()
const systemId = route.params.systemId as string

const loading = ref(false)
const processList = ref([])

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 获取流程列表
const fetchProcessList = async () => {
  try {
    loading.value = true
    const res = await getProcessList(systemId)
    processList.value = res.data || []
  } catch (error: any) {
    console.error('获取流程列表失败:', error)
  } finally {
    loading.value = false
  }
}
//导入流程
const handleImport = async (file: File) => {
  try {
    // 验证文件格式
    if (!file.name.endsWith('.xml')) {
      ElMessage.error('请上传 .xml 格式的文件')
      return false
    }

    // 验证文件大小（例如：限制5MB）
    const maxSize = 5 * 1024 * 1024
    if (file.size > maxSize) {
      ElMessage.error('文件大小不能超过5MB')
      return false
    }

    // 读取文件内容
    const reader = new FileReader()
    reader.readAsText(file)

    reader.onload = async (e) => {
      try {
        const xmlContent = e.target?.result as string
        
        // 将XML内容存储到sessionStorage
        sessionStorage.setItem('importedBpmnXML', xmlContent)
        
        // 跳转到新增页面，并带上导入标记
        router.push({
          path: `/system/${systemId}/workflows/create`,
          query: { imported: 'true' }
        })
      } catch (error) {
        ElMessage.error('文件解析失败')
      }
    }

    reader.onerror = () => {
      ElMessage.error('文件读取失败')
    }

    // 返回false阻止自动上传
    return false
  } catch (error) {
    ElMessage.error('导入失败')
    return false
  }
}
// 新增流程
const handleAdd = () => {
  router.push(`/system/${systemId}/workflows/create`)
}

// 查看流程
const handleView = (row: any) => {
  router.push(`/system/${systemId}/workflows/${row.id}/view`)
}

// 编辑流程
const handleEdit = (row: any) => {
  router.push(`/system/${systemId}/workflows/${row.id}/edit`)
}

// 修改状态
const handleChangeStatus = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确认${row.status === 1 ? '禁用' : '启用'}该流程吗？`, 
      '提示', 
      { type: 'warning' }
    )
    // TODO: 调用修改状态接口
    ElMessage.success('操作成功')
    await fetchProcessList()
  } catch (error) {
    // 用户取消操作
  }
}

// 删除流程
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认删除该流程吗？', '提示', {
      type: 'warning'
    })
    // TODO: 调用删除接口
    await deleteProcess(row.id)
    ElMessage.success('删除成功')
    await fetchProcessList()
  } catch (error) {
    // 用户取消操作
  }
}

onMounted(() => {
  fetchProcessList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.upload-btn {
  display: inline-block;
}
</style> 